﻿MvcPipe = function () {

    var _LoadStyleSheet = function (path, media, fn, scope) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.setAttribute('href', path);
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('type', 'text/css');
        link.setAttribute("media", media);

        var sheet, cssRules;
        if ('sheet' in link) {
            sheet = 'sheet'; cssRules = 'cssRules';
        }
        else {
            sheet = 'styleSheet'; cssRules = 'rules';
        }

        var successTimeoutId = setInterval(function () {
            try {
                if (link[sheet] && link[sheet][cssRules].length) {
                    clearInterval(successTimeoutId);
                    clearTimeout(successTimeoutId);
                    clearInterval(failureTimeoutId);
                    clearTimeout(failureTimeoutId);
                    fn.call(scope || window, true, link);
                }
            } catch (e) { } finally { }
        }, 10);

        var failureTimeoutId = setTimeout(function () {
            clearInterval(successTimeoutId);
            clearTimeout(successTimeoutId);
            clearInterval(failureTimeoutId);
            clearTimeout(failureTimeoutId);
            head.removeChild(link);
            fn.call(scope || window, false, link);
        }, 15000);

        head.appendChild(link);

        return link;
    };

    var _ActivatePipelet = function (pipelet) {
        document.getElementById(pipelet.Name).innerHTML = pipelet.Content;

        var head = document.getElementsByTagName('head')[0];

        for (var index in pipelet.JavascriptReferences) {
            var link = document.createElement('script');
            link.setAttribute('type', "text/javascript");
            link.setAttribute("src", pipelet.JavascriptReferences[index]);
            head.appendChild(link);
        }
    };

    return {
        ReceivePipelet: function (pipelet) {
            var stylesheetCount = pipelet.CssReferences.length;

            if (stylesheetCount == 0) {
                _ActivatePipelet(pipelet);
            }

            for (var index in pipelet.CssReferences) {
                var cssReference = pipelet.CssReferences[index];

                _LoadStyleSheet(cssReference.Url, cssReference.Media, function (success, node) {
                    stylesheetCount--;
                    if (stylesheetCount == 0) {
                        _ActivatePipelet(pipelet);
                    }
                });
            }
        }
    };
} ();
